from odoo import fields, models, api
from odoo.exceptions import UserError


class RPParcel(models.Model):
    _name = "rp.parcel"
    _description = '包裹'
    _rec_name = 'code'

    def _default_get_kg(self):
        kg = self.env['uom.uom'].search([('name', '=', 'kg')])
        return kg.id if kg else False

    def _default_get_cm(self):
        cm = self.env['uom.uom'].search([('name', '=', 'cm')])
        return cm.id if cm else False

    def _default_get_cm3(self):
        cm = self.env['uom.uom'].search([('name', '=', 'cm³')])
        return cm.id if cm else False

    rp_ship_order_id = fields.Many2one(string='从属运输订单', comodel_name='rp.ship.order', ondelete='cascade')

    code = fields.Char(string='包裹编号', default='RP_P/20230101/*****', readonly=True, copy=False, index=True)
    rp_package_standards_id = fields.Many2one(string='包裹模板', comodel_name='rp.package.standards')

    weight = fields.Float(string='重量', required=True)
    weight_uom_id = fields.Many2one(string='重量单位', comodel_name='uom.uom', domain=[('category_id', '=', 2)], default=_default_get_kg)
    weight_desc = fields.Char(string='重量描述', compute='_depends_fill_weight', store=True)

    depth = fields.Float(string='长度', required=True)
    width = fields.Float(string='宽度', required=True)
    height = fields.Float(string='高度', required=True)
    length_uom_id = fields.Many2one(string='长度单位', comodel_name='uom.uom', domain=[('category_id', '=', 4)], default=_default_get_cm)
    dimension_desc = fields.Char(string='尺寸描述', compute='_depends_fill_dimension', store=True)

    volume = fields.Float(string='体积', compute='_depends_compute_volume', store=True)
    volume_uom_id = fields.Many2one(string='体积单位', comodel_name='uom.uom', domain=[('category_id', '=', 6)], default=_default_get_cm3)
    volume_desc = fields.Char(string='体积描述', compute='_depends_fill_volume', store=True)

    desc = fields.Text(string='描述')
    values = fields.Float(string='总价值', digits=(8, 3), compute='_depends_compute_values', store=True, readonly=False)
    currency_id = fields.Many2one(string='货币单位', comodel_name='res.currency', default=lambda self: self.env.company.currency_id)

    rp_item_ids = fields.One2many(string='下属物品', comodel_name='rp.item', inverse_name='rp_parcel_id')
    package_photo_ids = fields.Many2many(string='包裹图片', comodel_name='ir.attachment', column1='rp_parcel_id', column2='ir_attachment_id', copy=False)

    @api.model_create_multi
    def create(self, vals_list):
        for vals in vals_list:
            vals['code'] = self.env['ir.sequence'].sudo().next_by_code('rp.parcel') or '/'
        return super(RPParcel, self).create(vals_list)

    def write(self, vals):
        state = self.rp_ship_order_id.state
        if state in ['done', 'invoiced']:
            raise UserError('订单已支付完成或已开票，拒绝进行修改！')
        return super(RPParcel, self).write(vals)

    @api.onchange('rp_package_standards_id')
    def _onchange_rp_package_standards_id(self):
        if self.rp_package_standards_id:
            self.write({
                'weight': self.rp_package_standards_id.weight,
                'weight_uom_id': self.rp_package_standards_id.weight_uom_id,
                'depth': self.rp_package_standards_id.depth,
                'width': self.rp_package_standards_id.width,
                'height': self.rp_package_standards_id.height,
                'length_uom_id': self.rp_package_standards_id.length_uom_id,
            })

    @api.depends('weight', 'weight_uom_id')
    def _depends_fill_weight(self):
        for s in self:
            weight = str(s.weight) if s.weight else ''
            uom = s.weight_uom_id.name if s.weight_uom_id else ''
            s.update({'weight_desc': "{} {}".format(weight, uom)})

    @api.depends('depth', 'width', 'height', 'length_uom_id')
    def _depends_fill_dimension(self):
        for s in self:
            depth = str(s.depth) if s.depth else ''
            width = str(s.width) if s.width else ''
            height = str(s.height) if s.height else ''
            uom = s.length_uom_id.name if s.length_uom_id else ''
            s.update({'dimension_desc': "{} / {} / {} {}".format(depth, width, height, uom)})

    @api.depends('depth', 'width', 'height')
    def _depends_compute_volume(self):
        for s in self:
            if s.depth and s.width and s.height:
                s.update({'volume': float(s.depth * s.width * s.height)})

    @api.depends('volume', 'volume_uom_id')
    def _depends_fill_volume(self):
        for s in self:
            volume = str(s.volume) if s.volume else ''
            uom = s.volume_uom_id.name if s.volume_uom_id else ''
            s.update({'volume_desc': '{} - {}'.format(volume, uom)})

    @api.depends('rp_item_ids')
    def _depends_compute_values(self):
        for s in self:
            if s.rp_item_ids:
                values = 0.0
                for item in s.rp_item_ids:
                    if item.value:
                        values += item.value
                s.update({'values': values})
